package com.atguigu.gulimaill.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimaill.search.config.GulimaillElasticsearchConfig;
import com.atguigu.gulimaill.search.constant.EsConstant;
import com.atguigu.gulimaill.search.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductSaveServiceImpl  implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    /**
     *
     * @param skuEsModelList
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {
        //给es建立一个索引
        // 建立好映射关系
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModelList) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimaillElasticsearchConfig.COMMON_OPTIONS);
        // TODO 如果批量错误 可以在这里处理

        List<String> collect = Arrays.asList(bulk.getItems()).stream().map(item -> item.getId()).collect(Collectors.toList());
        System.out.println("商品上架错误{}:"+collect);
        return bulk.hasFailures();
    }
}
